package loader

import (
	"encoding/json"
	"fmt"
	"io/ioutil"

	"gitee.com/zhongguo168a/gocodes/datax/coderx"
	"gitee.com/zhongguo168a/gocodes/datax/mapx"
	"gitee.com/zhongguo168a/gocodes/datax/schemax"
	"gitee.com/zhongguo168a/gocodes/myx/errorx"
)

func Load(path string) (err error) {
	file, readerr := ioutil.ReadFile(path)
	if readerr != nil {
		err = errorx.Wrap(err, fmt.Sprintf("read file %v", path))
		return
	}
	schemamap := map[string]interface{}{}
	err = json.Unmarshal(file, &schemamap)
	if err != nil {
		err = errorx.Wrap(err, fmt.Sprintf("json.Unmarshal"))
		return
	}

	return LoadMap(schemamap)
}

func LoadMap(schemamap map[string]interface{}) (err error) {
	schemas := mapx.Array(schemamap, "schemas")
	for _, val := range schemas {
		m := val.(map[string]interface{})

		obj, derr := coderx.NewMapToRef().SetSource(m).Create()
		if derr != nil {
			err = errorx.Wrap(derr, fmt.Sprintf("decoder"))
			return
		}

		_ = schemax.AddDecl(obj.(schemax.IDecl))

	}

	return
}
